package com.xiebishe.mylibrary.tools;

import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.xiebishe.mylibrary.common.WindowUtils;

public class KeyboardStatusDetector {

    private static final int SOFT_KEY_BOARD_MIN_HEIGHT = WindowUtils.getScreenHeight() / 3;


    private KeyboardVisibilityListener mVisibilityListener;
    private View mObseverView;

    boolean mIsSoftKeyboardShowing = false;


    //布局监听器，用来获取键盘状态
    private ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //判断窗口可见区域大小
            Rect r = new Rect();
            mObseverView.getWindowVisibleDisplayFrame(r);
            int heightDiff = (mObseverView.getHeight() - r.top) - (r.bottom - r.top);//(screenHeight-r.top)为屏幕(不包括状态栏和虚拟按键栏)的高度
            boolean isKeyboardShowing = heightDiff > SOFT_KEY_BOARD_MIN_HEIGHT;
            //如果之前软键盘状态为显示，现在为关闭，或者之前为关闭，现在为显示，则表示软键盘的状态发生了改变
            if ((mIsSoftKeyboardShowing && !isKeyboardShowing) || (!mIsSoftKeyboardShowing && isKeyboardShowing)) {
                mIsSoftKeyboardShowing = isKeyboardShowing;
                if (mVisibilityListener != null) {
                    mVisibilityListener.onVisibilityChanged(mIsSoftKeyboardShowing, heightDiff);
                }
            }
        }
    };

    public KeyboardStatusDetector registerActivity(AppCompatActivity a) {
        mObseverView = a.getWindow().getDecorView();
        mObseverView.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);
        a.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                destorySelf();
            }
        });
        return this;
    }

    public KeyboardStatusDetector setListener(KeyboardVisibilityListener listener) {
        mVisibilityListener = listener;
        return this;
    }


    private void destorySelf() {
        if (mObseverView != null) {
            mObseverView.getViewTreeObserver().removeOnGlobalLayoutListener(mLayoutChangeListener);
            mObseverView = null;
        }
        mVisibilityListener = null;
    }


    public interface KeyboardVisibilityListener {
        void onVisibilityChanged(boolean keyboardVisible, int height);
    }

}
